<script setup lang="ts">
import * as  THREE from 'three';
import {onMounted, ref} from "vue";
import type { Ref} from "vue";

const canvesRef = ref<HTMLCanvasElement | null>(null);
const scene:Ref<any> = ref();
const camera:Ref<any> = ref(null)
const renderer:Ref<any> = ref(null)
// 浏览器视窗宽度
// 浏览器视窗宽度
const width = ref(window.innerWidth);
const height = ref(window.innerHeight);

const init = () => {
  scene.value = new THREE.Scene();
  addCamera(scene.value);
  createCube(scene.value);
  addLight(scene.value);
  render(scene.value, camera.value);
}

/**
 * 创建立方体
 * @param scene
 */
const createCube = (scene: THREE.Scene) => {
  const geometry = new THREE.BoxGeometry(10, 10, 10);
  const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });

  const mesh = new THREE.Mesh(geometry, material);
  scene.add(mesh);
}

/**
 * 添加电光源
 * @param scene
 */
const addLight = (scene: THREE.Scene) => {
  const light = new THREE.DirectionalLight(0xffffff, 1);
  light.position.set(0, 0, 100);
  scene.add(light);
}

/**
 * 添加透视相机
 * @param scene
 */
const addCamera = (scene: THREE.Scene) => {
  const c = new THREE.PerspectiveCamera(75, 1, 0.1, 1000);
  c.position.z = 100;
  c.lookAt(0, 0, 0)
  scene.add(c);
  camera.value = c;
}

/**
 * 渲染
 */
const render = (scene: THREE.Scene, camera: THREE.Camera) => {
  const r = new THREE.WebGLRenderer({
    antialias: true,
  });
  r.setSize(width.value, height.value);
  renderer.value = r;
  if (camera && scene) {
    // r.render(scene, camera);
    r.render(scene, camera); //执行渲染操作

    canvesRef.value?.appendChild(r.domElement);
  } else {
    console.log('camera  is null', camera.value)
    console.log('scene is null', scene.value)
  }
}


onMounted(() => {
  console.log('game init in mounted')
  init();
})
</script>

<template>
  <div class="game-wrapper">
    <div class="title">跳一跳</div>
    <div ref="canvesRef" class="canves-wrapper"></div>
  </div>
</template>

<style scoped>
.game-wrapper {
  width: 100%;
  height: 100%;
  background-color: #000;
  position: relative;
}
.title {
  position: absolute;
  width: 100%;
  height: 40px;
  text-align: center;
}
.canves-wrapper {
  position: absolute;
  top: 80px;
  left: 50%;
  transform: translateX(-50%);
  width: 400px;
  height: 300px;
}
</style>
